﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Twitter;

namespace PKTwitter
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            ValidateUserNPsw();
            string username = tbxUser.Text,
                password = tbxPassword.Text;

            tbxPassword.Enabled = false;
            tbxUser.Enabled = false;

            Twitter.Twitter twitter = Twitter.Twitter.GetInstance();
            twitter.OnCredentialsVerified += new EventHandler<TwitterEventArgs>(twitter_OnCredentialsVerified);

            twitter.VerifyCredentialsAsync(username, password);
            this.Cursor = Cursors.WaitCursor;
        }

        void twitter_OnCredentialsVerified(object sender, TwitterEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new EventHandler<TwitterEventArgs>(twitter_OnCredentialsVerified), new object[]{sender, e});
            }
            else
            {
                tbxPassword.Enabled = true;
                tbxUser.Enabled = true;
                this.Cursor = Cursors.Default;

                if (e.ex == null && Convert.ToBoolean(e.Status == "OK"))
                {
                    string username = tbxUser.Text,
                    password = tbxPassword.Text;
                    Twitter.Twitter twitter = Twitter.Twitter.GetInstance();
                    twitter.Login(username, password);
                    PKTwitter pkTwitter = PKTwitter.GetInstance() as PKTwitter;
                    pkTwitter.SetTextInTheStatusBar(string.Format("You are loggen in Twitter as {0}", username));
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Ups! u r not user, you know??");
                }
            }
        }
        
        private void ValidateUserNPsw()
        {
            if (string.IsNullOrEmpty(tbxUser.Text) || string.IsNullOrEmpty(tbxPassword.Text))
                throw new Exception("U must write an user or a password");
        }

        private void TestUserNPsw(string username, string password)
        {
            Twitter.Twitter twitter = Twitter.Twitter.GetInstance();

            if (!twitter.VerifyCredentials(username, password))
                throw new Exception("Guess what? Ur credentials doesnt work, dude!");
        }

        
    }
}
